package logic

import (
	"blog/models/mysql"
	"blog/models/redis"
	"blog/pkg"
	"context"
	"fmt"

	"blog/blogrpc/blogrpc"
	"blog/blogrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *blogrpc.LoginRequest) (*blogrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get(l.ctx, "sendsms"+in.Account)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}
	captcha := redis.Rdb.Get(l.ctx, "captcha"+in.Account)
	if captcha.Val() != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误")
	}
	var blog mysql.BlogUser
	mysql.DB.Where("account=?", in.Account).Find(&blog)
	if blog.ID == 0 {
		return nil, fmt.Errorf("用户不存在,请前去注册")
	}
	if blog.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码不正确")
	}
	return &blogrpc.LoginResponse{
		Id: int64(blog.ID),
	}, nil
}
